package com.kaiyidiannao.common.BaiduMap;

/**
 * Created by wzg on 14-4-11.
 */

import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.mapapi.map.*;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.kaiyidiannao.activity.foodpalace.FoodPalaceDetail;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.main.R;
import com.kaiyidiannao.model.bean.PlayBean;
import com.kaiyidiannao.view.ActionBarView;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaiduMapActivity extends Activity {

    private MapView mapView = null;
    private MapController mapController;
    private ActionBarView actionBarView;
    //先写死，最后要改的经纬度
    private Double nowLongitude = DataCenter.nowLongitude;
    private Double nowLatitude = DataCenter.nowLatitude;
    private Double shopLongitude ;
    private Double shopLatitude ;
    private int maxLat = 0;
    private int minLat = 0;
    private int maxLon = 0;
    private int minLon = 0;
    private HttpGet request;
    private DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
    private String resultStr;
    private int size= 0;
    private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    private PoiOverlay poiOverlay;
    private PoiOverlay poiOverlay1;
    private String title ;
    private String tel;
    private int a = 0;
    private int selectedPoiItemIndex;
    private MyLocationOverlay myLocationOverlay;
    private LayoutInflater inflater;
    private String address;
    private String catid;
    private String thumb;
    private String star;
    private PlayBean bean ;
    private ArrayList<PlayBean> listBean = new ArrayList<PlayBean>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.baidumap_view);
        inflater = LayoutInflater.from(this);
        mapView=(MapView)findViewById(R.id.mapsView);
        mapController=mapView.getController();
        Intent intent = getIntent();
        catid = intent.getStringExtra("catid");
        nowLatitude = Double.parseDouble(intent.getStringExtra("nowLatitude"));
        nowLongitude = Double.parseDouble(intent.getStringExtra("nowLongitude"));
        size = Integer.parseInt(intent.getStringExtra("listSize"));
        if (myLocationOverlay != null) {
            mapView.getOverlays().remove(myLocationOverlay);
        }

        myLocationOverlay = new MyLocationOverlay(mapView);
        LocationData locationData = new LocationData();
        locationData.latitude = nowLatitude;
        locationData.longitude = nowLongitude;
        myLocationOverlay.setData(locationData);

        //添加图层
        mapView.getOverlays().add(myLocationOverlay);

        mapView.refresh();
        initBaiduMap();

    }

    public void initBaiduMap(){
        GeoPoint point =new GeoPoint((int)(nowLatitude*1E6),(int)(nowLongitude* 1E6));
        mapController.setCenter(point);//设置地图中心点
        mapController.setZoom(12);//设置地图zoom级别
        actionBarView = (ActionBarView)findViewById(R.id.baiduactionbar);
        actionBarView.button_right_icon2.setVisibility(View.VISIBLE);
        actionBarView.button_right_icon2.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.delicious_map_04));
        actionBarView.button_right_icon1.setVisibility(View.VISIBLE);
        actionBarView.button_right_icon1.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.delicious_map_03));
        actionBarView.button_right_icon1.setMaxWidth(10);
        doReceviceLocation();

    }

    public void doReceviceLocation() {
        final String url = "http://api.map.baidu.com/geosearch/v3/nearby?" +
                "ak=kFihD1CLl3Sru4dNpdOvQ5RV&" +
                "geotable_id=59254&location="+nowLongitude+","+nowLatitude+"&radius=10000&page_size="+(size+1)
                +"&filter=catid:"+catid+","+catid;
        Log.d("http url", url);
        request = new HttpGet(url);
        int timeout = 30000;
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(params, timeout);
        HttpConnectionParams.setConnectionTimeout(params, timeout);

        defaultHttpClient.setParams(params);
        AsyncTask<Integer, Integer, Integer> task = new AsyncTask<Integer, Integer, Integer>() {
            @Override
            protected Integer doInBackground(Integer... params) {
                requestHttp(request);
                return 0;
            }

            @Override
            protected void onPostExecute(Integer integer) {
                Toast.makeText(BaiduMapActivity.this, "访问成功", Toast.LENGTH_SHORT).show();
                Log.d("", "onPostExecute is finish");
                jsonbt();
                Log.d("nowLatitude",nowLatitude +  "-----" + shopLongitude);

            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

        };
        task.execute(0);
        Log.d("http url", "you is doReceviceLocation");
    }
//待解决如何给图片上加文字
    public void displayPoi() {
        Log.d("displayPoi","displayPoi" +"  "+ list.size());
        Drawable mark1 = getResources().getDrawable(R.drawable.food_14);
        poiOverlay = new PoiOverlay(mark1,mapView);
        for (int i = 0; i < list.size(); i++) {
            Log.d("shopLongitude",list.get(i).get("shopLongitude")+"   "+"shopLongitude"+list.get(i).get("shopLongitude"));
            GeoPoint p = new GeoPoint((int) (Double.parseDouble(list.get(i).get("shopLatitude") + "") * 1E6),
                    (int) ((Double.parseDouble(list.get(i).get("shopLongitude") + "") * 1E6)));
            Log.d("displayPoi", p.getLatitudeE6() + " and " + p.getLongitudeE6());
            PoiItem item1 = new PoiItem(p, "item1", "item1");
            item1.setMarker(mark1);
            poiOverlay.addItem(item1);
        }

        for (int i = 0; i < poiOverlay.getAllItem().size(); i++) {
            OverlayItem item = (OverlayItem) poiOverlay.getAllItem().get(i);
            GeoPoint geoPoint = item.getPoint();
            int lat = geoPoint.getLatitudeE6();
            int lon = geoPoint.getLongitudeE6();
            maxLat = Math.max(lat, maxLat);
            minLat = Math.min(lat, minLat);
            maxLon = Math.max(lon, maxLon);
            minLon = Math.min(lon, minLon);
        }
        mapController.zoomToSpan(Math.abs(maxLat - minLat), Math.abs(maxLon - minLon));
        mapController.animateTo(new GeoPoint((maxLat + minLat) / 2, (maxLon + minLon) / 2));
        mapView.getOverlays().add(poiOverlay);
        mapView.getOverlays().add(poiOverlay1);
        mapView.refresh();
    }

    public void jsonbt() {
        try {
            Log.d("jsonbt", "BaiduActivity jsonbt");
            JSONObject rootJsonObject = new JSONObject(resultStr);
            Log.d("http resultStr",resultStr);
            JSONArray poilistJsonArray = rootJsonObject.optJSONArray("contents");
            Log.d("jsonbt",poilistJsonArray.length()+"------");
            if (poilistJsonArray == null) {
                Toast.makeText(this, "查不到结果哦", Toast.LENGTH_SHORT).show();
                return;
            }
            for (int i = 0; i < poilistJsonArray.length(); i++) {
                JSONObject poiJsonObject = (JSONObject) poilistJsonArray.get(i);
                String locations = poiJsonObject.get("location")+"";
                locations = locations.substring(1, locations.length() - 1);
                String locationes [] = locations.split(",");
                shopLatitude = Double.parseDouble(locationes[1]);
                shopLongitude = Double.parseDouble(locationes[0]);
                Log.d("BaiduLongitude",shopLatitude +"-----"+shopLongitude);
                Map<String, Object> map = new HashMap<String, Object>();
                title = (String) poiJsonObject.get("title");
                address = (String) poiJsonObject.get("address");
                catid = poiJsonObject.getInt("catid")+"";
                map.put("shopLongitude", shopLongitude);
                map.put("shopLatitude", shopLatitude);
                map.put("address",address);
                map.put("title", title);
                String itemid = poiJsonObject.getString("itemid");
//                String star = poiJsonObject.getString("star");
//                thumb = poiJsonObject.getString("thumb");
                bean = new PlayBean();
                bean.setCatid(catid);
//                bean.setThumb(thumb);
                bean.setTitle(title);
                bean.setAddress(address);
                bean.setItemid(itemid);
//                bean.setStar(star);
                listBean.add(bean);
                Log.d("jsonbtmapSize", map.size() + "  BaiduActivityListSize  ");
                list.add(map);
                Log.d("jsonbtListSize", list.size() + "  BaiduActivityListSize  ");
                if (nowLatitude > shopLatitude) {
                    maxLat = (int) (nowLatitude * 1E6);
                    minLat = (int) (shopLatitude * 1E6);
                } else {
                    minLat = (int) (nowLatitude * 1E6);
                    maxLat = (int) (shopLatitude * 1E6);
                }

                if (nowLongitude > shopLongitude) {
                    maxLon = (int) (nowLongitude * 1E6);
                    minLon = (int) (shopLongitude * 1E6);
                } else {
                    maxLon = (int) (shopLongitude * 1E6);
                    minLon = (int) (nowLongitude * 1E6);
                }
            }

            displayPoi();
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mapController.zoomToSpan(Math.abs(maxLat - minLat), Math.abs(maxLon - minLon));
                    mapController.animateTo(new GeoPoint((maxLat + minLat) / 2, (maxLon + minLon) / 2));
                    mapView.refresh();
                }
            }, 300);
        } catch (JSONException e) {
            Log.e("jsonBt" + "error", e.getMessage().toString());
        }
    }


    public void requestHttp(HttpGet request) {
        try {
            HttpResponse response = defaultHttpClient.execute(request);
            InputStream inputStream = response.getEntity().getContent();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int length;
            while ((length = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, length);
            }
            outputStream.close();
            inputStream.close();
            resultStr = outputStream.toString("UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class PoiOverlay extends ItemizedOverlay {

        public PoiOverlay(Drawable drawable, MapView mapView) {
            super(drawable, mapView);
        }



        @Override
        public boolean onTap(GeoPoint geoPoint, MapView mapView) {
            Log.d("OnTap", geoPoint.getLatitudeE6() + "  this is onTap");
            return super.onTap(geoPoint, mapView);
        }

        @Override
        protected boolean onTap(int i) {
            Log.d("OnTap", i + "  点点点啊");
            selectedPoiItemIndex = i;
            PopupOverlay popupOverlay = new PopupOverlay(mapView,new PopupClickListener() {
                @Override
                public void onClickedPopup(int i) {
                    Log.d("popupOnTap",i +"");
                    Intent intent = new Intent(BaiduMapActivity.this, FoodPalaceDetail.class);
                    Bundle bundle = new Bundle();
                    Log.d("FoodPalaceDetailItemidBaidu",listBean.get(i).getItemid()+"------");
                    bundle.putSerializable("playBean",listBean.get(i));
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            });
            PoiItem item = (PoiItem) poiOverlay.getItem(i);
            View popup = inflater.inflate(R.layout.baidu_popup, null);
            TextView titleTextView = (TextView) popup.findViewById(R.id.baidupop);
            titleTextView.setText((String) list.get(i).get("title"));
            popupOverlay.showPopup(popup, item.getPoint(), item.getMarker().getIntrinsicHeight());
            return super.onTap(i);
        }
    }

    class PoiItem extends OverlayItem {

        private int type;

        public PoiItem(GeoPoint geoPoint, String s, String s2) {
            super(geoPoint, s, s2);
        }

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }

    }
}
